/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2015年3月16日         luwei
 */

package com.coocaa.app.gamecenter.pages.list;

import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.LinearLayout;

import com.coocaa.app.gamecenter.framework.ui.GameCenterBaseLayout;
import com.coocaa.app.gamecenter.framework.ui.LoadMoreGridView.LoadMoreDataCallback;
import com.coocaa.app.gamecenter.pages.detail.DetailActivity;
import com.coocaa.framework.ui.view.ScrollGridView;
import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.framework.utils.SafeAsyncTask;
import com.coocaa.x.uipackage.widget.SlideFocusView;
import com.skyworth.framework.skysdk.ipc.SkyStartActivity;
import com.tianci.appstore.R;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.widget.TipToast;
import com.tianci.appstore.utils.SkyConstants;

import java.util.HashMap;
import java.util.List;

public class GameCenterListLayout extends GameCenterBaseLayout implements AdapterView.OnItemSelectedListener,AdapterView.OnItemClickListener {

    private ScrollGridView mGridView = null;
    private LoadMoreDataCallback mLoadMoreDataCallback = null;
    private boolean mIsLoading = false;
    private int mHasLoadPage = 0;
    private GameListAdapter mAdapter = null;
    private int mTotalNum = 0;
    private boolean mIsFirst = true;
    private LinearLayout gridLayout = null;
    private SlideFocusView.FocusViewRevision mRevision = new SlideFocusView.FocusViewRevision(SkyConstants.Div(35), SkyConstants.Div(68));

    public GameCenterListLayout(Context context) {
        super(context);
        addGridView();
        addFuncButtonLayout();
        setFocusable(false);
        setFocusableInTouchMode(false);
        hideMyGameBtn();
    }

    private void addGridView() {
        gridLayout = new LinearLayout(mContext);
        mGridView = new ScrollGridView(mContext);
        mGridView.setStretchMode(GridView.NO_STRETCH);
        mGridView.setVerticalSpacing(Div(43));
        mGridView.setNumColumns(3);
        mGridView.setHorizontalSpacing(Div(53 + 474));
        mGridView.setSelector(android.R.color.transparent);
        mGridView.setThumbV(R.drawable.game_center_progress_bar);
        mGridView.setOverScrollMode(OVER_SCROLL_NEVER);
        mGridView.setOnItemClickListener(this);

        //mGridView不添加到layout中当activity被全屏覆盖时mGridView会恢复到初始位置，不知为何？
        LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(Div(1657),
                Div(760), Gravity.CENTER_VERTICAL);
        gridLayout.addView(mGridView, lparams);

        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                Gravity.CENTER);
        params.leftMargin = Div(63);
        addView(gridLayout, params);
        mGridView.setAnimation(R.anim.grid_anim);
        mAdapter = new GameListAdapter(mContext);
        mGridView.setAdapter(mAdapter);
        itemSelectedEvent.registerView(mGridView,mRevision,this);
    }

    public void setLoadMoreCallback(LoadMoreDataCallback callback) {
        this.mLoadMoreDataCallback = callback;
    }

    public void setTotalNum(int total) {
        this.mTotalNum = total;
    }

    public void loadData() {
        new CountryAsyncTask(true).execute();
    }

    public void initFocus() {
        postDelayed(new Runnable() {
            @Override
            public void run() {
                mGridView.requestFocus();
                mGridView.setFocus(0);
                openAnimation(true);
            }
        }, 200);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        LogUtils.i("luwei", "count = " + mAdapter.getCount() + " index " + position);
        if (mAdapter.getCount() - position < 5 * 3 && mAdapter.getCount() < mTotalNum && !mIsLoading) {
            new CountryAsyncTask(true).execute();
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        SkyListAppData data = (SkyListAppData)parent.getAdapter().getItem(position);
        if (LiteAppApplication.checkNetworkConnection(TipToast.showNetIsNotConnectedToastRunnable)) {
            Intent intent = new Intent("com.coocaa.gamecenter.detail");
            intent.putExtra(DetailActivity.INTENT_APPID_KEY, data.getId());
            intent.putExtra(DetailActivity.INTENT_PACKAGENAME_KEY, data.getPkgName());
//            mContext.startActivity(intent);
            HashMap<String,String> map = new HashMap<String,String>();
            SkyStartActivity.startActivity(mContext, mContext.getClass().getName(), intent, map, false);
        }
    }

    private class CountryAsyncTask extends SafeAsyncTask<List<SkyListAppData>> {
        public CountryAsyncTask(boolean showLoading) {
            mIsLoading = true;
        }

        @Override
        protected void onPreExecute() throws Exception {
            super.onPreExecute();
        }

        @Override
        public List<SkyListAppData> call() throws Exception {
            if (mLoadMoreDataCallback != null) {
                mHasLoadPage++;
                return mLoadMoreDataCallback.loadMordData(mHasLoadPage);
            }
            return null;
        }

        @Override
        protected void onSuccess(List<SkyListAppData> newItems) throws Exception {
            super.onSuccess(newItems);
            mAdapter.updateUI(newItems);
            if (mIsFirst) {
                initFocus();
                mIsFirst = false;
            }
        }

        @Override
        protected void onFinally() throws RuntimeException {
            super.onFinally();
            mIsLoading = false;
        }
    }

    @Override
    public void destory() {
        mAdapter.destory();
        mLoadMoreDataCallback = null;
        super.destory();
    }

    @Override
    public View getContentView() {
        // TODO Auto-generated method stub
        return gridLayout;
    }
}
